
using namespace System.Management.Automation
using namespace System.Management.Automation.Language
using namespace Microsoft.PowerShell
# 修改编码为 UTF8
[console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding

# by https://blog.mk1.io/posts/powerful-powershell
#f45873b3-b655-43a6-b217-97c00aa0db58 PowerToys CommandNotFound module

Import-Module -Name Microsoft.WinGet.CommandNotFound
#f45873b3-b655-43a6-b217-97c00aa0db58

# 引入 posh-git
Import-Module posh-git
Import-Module posh-docker
Import-Module posh-cargo
# 引入 ps-read-line`
# Import-Module PSReadLine
Import-Module PSColor
function TestCommand {
    param (
        [Parameter(Mandatory = $true)]
        [string]$CommandName
    )
    # 使用 Get-Command 尝试获取指定命令的信息
    $command = Get-Command -Name $CommandName -ErrorAction SilentlyContinue
    # 如果成功获取到命令信息，则命令存在，返回 $true；否则返回 $false
    if ($command) {
        return $true
    }
    return $false
}

# 启动 starship
# $ENV:STARSHIP_CONFIG = "$HOME\.config\starship.toml"
# $ENV:STARSHIP_CACHE = "$HOME\.config\starship.toml"
# Invoke-Expression (&starship init powershell)

# 加载 oh-my-posh
oh-my-posh init pwsh --config "$env:POSH_THEMES_PATH\emodipt-extend.omp.json" | Invoke-Expression

# 加载 fnm
# hul10
fnm env --use-on-cd | Out-String | Invoke-Expression

# 加载 z
try{
    Rg-Test-Command zoxide
    Invoke-Expression (& { (zoxide init powershell | Out-String) })
}catch{
    Write-Debug "zoxide not found"
}

# 加载 rustup completions
try{
    Rg-Test-Command rustup
    rustup completions powershell | Out-String | Invoke-Expression
}catch{
    Write-Debug "rustup not found"
}


## PSReadLine
# 历史记录的切换
Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward

# 使用历史记录进行脚本提示
Set-PSReadLineOption -PredictionSource History

# 补全括号和引号
Set-PSReadLineOption -HistorySearchCursorMovesToEnd
Set-PSReadlineKeyHandler -Key Tab -Function Complete

# 插入对应的引号
Set-PSReadLineKeyHandler -Chord '"',"'" `
                         -BriefDescription SmartInsertQuote `
                         -LongDescription "Insert paired quotes if not already on a quote" `
                         -ScriptBlock {
    param($key, $arg)

    $line = $null
    $cursor = $null
    [PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)

    if ($line.Length -gt $cursor -and $line[$cursor] -eq $key.KeyChar) {
        # Just move the cursor
        [PSConsoleReadLine]::SetCursorPosition($cursor + 1)
    }
    else {
        # Insert matching quotes, move cursor to be in between the quotes
        [PSConsoleReadLine]::Insert("$($key.KeyChar)" * 2)
        [PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
        [PSConsoleReadLine]::SetCursorPosition($cursor - 1)
    }
}